package client.ui.view.panel.good;

import client.UserState;
import client.assets.Icons;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Auction;
import client.entity.User;
import client.ui.component.button.MaterialButton;
import client.ui.component.card.PictureLabel;
import client.ui.component.edittext.TextEdit;
import client.ui.component.layout.VFlowLayout;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialBorder;
import client.ui.util.MaterialColors;
import client.entity.Good;
import client.ui.view.MainPage;
import client.ui.view.base.FrameBase;
import client.ui.view.base.PanelControl;
import client.ui.view.panel.main.CartPanel;
import client.ui.view.panel.main.ChatPanel;
import client.ui.view.panel.main.MyDataPanel;
import client.util.ImageUtil;

import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class BuyPanel extends JPanel implements PanelControl, ActionListener {
    private Auction auction;
    private Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
    private TextEdit numEdit;
    private TextEdit priceEdit;
    private Good goodInfo;
    private JPanel auctionPanel;
    private JLabel duringTime;
    private JLabel priceNow;
    private JLabel headImageLabel;
    private JLabel usernameLabel;
    private PanelControl goodDescriptionPanel;
    private String ownerName;
    private Integer ownerId;
    public BuyPanel(Good good, PanelControl goodDescriptionPanel){
        super();
        this.goodInfo = good;
        this.goodDescriptionPanel = goodDescriptionPanel;
        initial();
        Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
        //获取用户名
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                int userId = Controller.USER_CONTROL.getUserIdByGoodId(goodInfo.getGoodId());
                ResponseEntity responseEntity = Controller.USER_CONTROL.getOtherUserInfo(userId);
                if (responseEntity.getCode() == 0){
                    User user = JSONObject.parseObject(responseEntity.getData(), User.class);
                    ownerId = user.getUserId();
                    ownerName = user.getUserName();
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            usernameLabel.setText("用户:" + user.getUserName());
                            usernameLabel.setToolTipText(usernameLabel.getText());
                        }
                    });
                }
            }
        });
        //获取头像
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                int userId = Controller.USER_CONTROL.getUserIdByGoodId(goodInfo.getGoodId());
                ImageIcon headIcon = Controller.USER_CONTROL.getHeadImage(userId, 45);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        headImageLabel.setIcon(headIcon);
                    }
                });
            }
        });
    }

    private void initial(){
        this.setLayout(new BorderLayout());
        this.setBorder(MaterialBorder.FOCUSED_LINE_BORDER);
        this.setBackground(MaterialColors.WHITE);
        //提供的用户
        JPanel provideUser = new JPanel();
        headImageLabel = new JLabel(ImageUtil.getImageIcon(Icons.ghost,null,45,45));
        usernameLabel = new JLabel("此商品属于机密");
        usernameLabel.setFont(ThisFont.MIDDLE_FONT);
        usernameLabel.setToolTipText(usernameLabel.getText());
        provideUser.setBackground(MaterialColors.WHITE);
        provideUser.add(headImageLabel);
        provideUser.add(usernameLabel);

        initAuctionPanel();
        this.add(auctionPanel,BorderLayout.CENTER);
        Box buttonBox = Box.createHorizontalBox();
        buttonBox.setBorder(new EmptyBorder(12,12,12,12));
        MaterialButton contact = MaterialButton.BlueButton("联系卖家",null);
        contact.addActionListener(this);
        contact.setActionCommand("contact");
        MaterialButton favor = MaterialButton.BlueButton("收藏",null);
        favor.addActionListener(this);
        favor.setActionCommand("favor");
        MaterialButton buy = MaterialButton.BlueButton("购买",null);
        buy.addActionListener(this);
        buy.setActionCommand("buy");
        buttonBox.add(contact, Box.LEFT_ALIGNMENT);
        buttonBox.add(favor, Box.CENTER_ALIGNMENT);
        buttonBox.add(buy, Box.RIGHT_ALIGNMENT);

        this.add(provideUser, BorderLayout.NORTH);
        this.add(buttonBox, BorderLayout.SOUTH);
    }

    void initAuctionPanel(){
        CardLayout cardLayout = new CardLayout();
        this.auctionPanel = new JPanel(cardLayout);
        JPanel forbidden = new JPanel();
        numEdit = new TextEdit("输入您要购买的数量");
        numEdit.setText("1");
        PictureLabel pictureLabel = new PictureLabel(Icons.unavailable);
        pictureLabel.setMinimumSize(new Dimension(128,128));
        pictureLabel.setMinimumSize(new Dimension(128,128));
        forbidden.add(numEdit);

        auctionPanel.add("forbidden", forbidden);

        JPanel available = new JPanel(new VFlowLayout());
        JLabel label = new JLabel("正在拍卖:");
        label.setFont(ThisFont.BIG_BOLD_FONT);
        duringTime = new JLabel("拍卖时间:" + "2000-00-00~2000-00-01");
        duringTime.setFont(ThisFont.MIDDLE_FONT);
        priceNow = new JLabel("初始价位" + "￥ " + "0.00");
        priceNow.setFont(ThisFont.MIDDLE_FONT);
        priceEdit = new TextEdit("您的出价");

        //顺序不可改变
        available.add(label);
        available.add(duringTime);
        available.add(priceNow);
        available.add(priceEdit);

        auctionPanel.add("available",available);
        auctionPanel.setBorder(new LineBorder(MaterialColors.COSMO_BLUE));
        if (goodInfo.getAuctionId() != 0){
            cardLayout.show(auctionPanel,"available");
        } else {
            cardLayout.show(auctionPanel,"unavailable");
        }

    }

    @Override
    public void updatePanel(Object object) {
        if (object instanceof Good){
            goodInfo = (Good) object;
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    ResponseEntity responseEntity = Controller.AUCTION_CONTROL.getAuctionInfo(goodInfo.getAuctionId());
                    if (responseEntity.getCode() == 0){
                        auction = JSONObject.parseObject(responseEntity.getData(), Auction.class);
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                duringTime.setText("拍卖时间"+
                                        simpleDateFormat.format(auction.getStart())
                                        + "~" +
                                        simpleDateFormat.format(auction.getEnd()));
                                priceNow.setText("目前价位" + "￥" + auction.getMaxPrice()
                                        + "  最高价用户:"
                                        + ((UserState.getUser().getUserId().equals(auction.getUserId())) ? "您" : "他人")
                                );
                                priceEdit.setText(auction.getMaxPrice() + "");
                            }
                        });
                    }
                }
            });
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
        if ("contact".equals(e.getActionCommand())){
            if (ownerName != null || ownerId != null){
                PanelControl p = PanelControl.panels.get("ChatPanel");
                if (p instanceof ChatPanel){
                    ((ChatPanel) p).selectItem(ownerId, ownerName);
                    JFrame main = FrameBase.frameBaseList.get(0);
                    if (main instanceof MainPage){
                        main.setVisible(true);
                        main.setExtendedState(JFrame.NORMAL);
                        ((MainPage) main).actionPerformed(
                                new ActionEvent(main, ActionEvent.ACTION_PERFORMED, "chatList")
                        );
                    }
                }
            }
        } else if ("buy".equals(e.getActionCommand())){
            //确定购买
            if (JOptionPane.showConfirmDialog(this,"确定购买") == JOptionPane.YES_OPTION){
                if (goodInfo.getAuctionId() == 0){
                    try{
                        Integer.parseInt(numEdit.getText());
                        if (numEdit.getText().length() == 0){
                            numEdit.setText("1");
                        }
                    } catch (Exception e1){
                        numEdit.setErrorText("请输入合法数字");
                        return;
                    }
                } else {
                    try{
                        Double.parseDouble(priceEdit.getText());
                    } catch (Exception e1){
                        priceEdit.setErrorText("请输入正常的价格");
                        return;
                    }
                }
                priceEdit.setErrorText("");
                numEdit.setErrorText("");
                singleThreadExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        if (goodInfo.getAuctionId() == 0){
                            ResponseEntity responseEntity = Controller.GOOD_CONTROL.purchase(
                                    UserState.getToken(), goodInfo.getGoodId(), Integer.parseInt(numEdit.getText()));
                            if (responseEntity.getCode() == 0){
                                responseEntity = Controller.GOOD_CONTROL.getGoodInfo(goodInfo.getGoodId());
                                if (responseEntity.getCode() == 0){
                                    Good good = JSONObject.parseObject(responseEntity.getData(), Good.class);
                                    goodDescriptionPanel.updatePanel(good);
                                    PanelControl p = panels.get("MyDataPanel");
                                    if (p instanceof MyDataPanel){
                                        ((MyDataPanel) p).getMyGoodList();
                                    }
                                }
                                showMessage("购买成功");
                            } else if (responseEntity.getCode() == 1){
                                showMessage("货源不足");
                            } else if (responseEntity.getCode() == 2){
                                showMessage("您穷了");
                            } else {
                                showMessage("因为不可抗力您的请求失败了");
                            }
                        } else {
                            ResponseEntity responseEntity = Controller.AUCTION_CONTROL.bid(
                                    UserState.getToken(), goodInfo.getAuctionId(), Double.parseDouble(priceEdit.getText()));
                            if (responseEntity.getCode() == 0){
                                JOptionPane.showMessageDialog(BuyPanel.this,"出价成功");
                                priceNow.setText("目前价位" + "￥" + priceEdit.getText()
                                        + "  最高价用户:" + "您"
                                );
                            } else {
                                showMessage(responseEntity.getMessage());
                            }
                        }

                    }
                });
            }
        } else if ("favor".equals(e.getActionCommand())){
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    ResponseEntity responseEntity = Controller.GOOD_CONTROL.addCart(UserState.getToken(), goodInfo.getGoodId());
                    if (responseEntity.getCode() == 0){
                        showMessage("添加成功");
                        PanelControl panelControl = PanelControl.panels.get("CartPanel");
                        if (panelControl instanceof CartPanel){
                            ((CartPanel) panelControl).getCartList();
                        }
                    } else {
                        showMessage(responseEntity.getMessage());
                    }
                }
            });
        }
    }

    private void showMessage(String message){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(BuyPanel.this,message);
            }
        });
    }
}
